#!/bin/bash
# sed -i 's/\r//' file.txt
# 这个命令会删除文件 file.txt 中的所有回车符（\r），从而将 CRLF 转换为 LF。
# 修复Ubuntu虚拟机网络问题的脚本
# 功能：停止NetworkManager服务 -> 删除状态文件 -> 重启服务

show_help() {
    echo "Usage: $0 [--help]"
    echo "Fix missing network icon and connection issues in Ubuntu VMs"
    echo
    echo "This script performs the following steps:"
    echo "1. Stops NetworkManager service"
    echo "2. Removes /var/lib/NetworkManager/NetworkManager.state"
    echo "3. Restarts NetworkManager service"
    echo
    echo "Note: Requires root privileges. Run with sudo!"
    exit 0
}

# 显示帮助信息
if [[ "$1" == "--help" || "$1" == "-h" ]]; then
    show_help
fi

# 检查root权限
if [ "$(id -u)" -ne 0 ]; then
    echo "Error: This script must be run as root. Use sudo!" >&2
    exit 1
fi

# 确定正确的服务名称
if systemctl is-active NetworkManager &>/dev/null; then
    SERVICE_NAME="NetworkManager"
elif systemctl is-active network-manager &>/dev/null; then
    SERVICE_NAME="network-manager"
else
    echo "Error: NetworkManager service not found!" >&2
    exit 1
fi

# 执行修复操作
echo "Stopping $SERVICE_NAME..."
systemctl stop "$SERVICE_NAME"

echo "Removing NetworkManager state file..."
rm -f /var/lib/NetworkManager/NetworkManager.state

echo "Starting $SERVICE_NAME..."
systemctl start "$SERVICE_NAME"

# 显示结果
echo
echo "Operation completed successfully!"
echo "Network service should be restored within 10-15 seconds."
echo "If problems persist, reboot the system."